package com.dingding.service.user.core.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dao.impl.BaseDaoImpl;
import com.dingding.common.core.beans.WechatUser;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.service.user.core.dao.IWechatUserDao;

/**
 * @Description:微信公众号用户dao
 * @author fengshuonan
 * @date 2016年4月30日 下午2:41:29
 */
@Component("wechatUserDao")
public class WechatUserDaoImpl extends BaseDaoImpl<WechatUser> implements IWechatUserDao {

	private Logger log = Logger.getLogger(this.getClass());

	/**
	 * @Description: 添加用户关注公众号的信息
	 * @param wechatUser
	 * @author fengshuonan
	 * @return void
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void addUserSubscribe(WechatUser wechatUser) {

		try {
			this.save(wechatUser);
		} catch (Exception e) {
			log.error(" 添加用户关注公众号的信息 出错 ！");
		}
	}

	/**
	 * @Description: 验证该公众号是否已经关注
	 * @param openId
	 *            微信公众号
	 * @author fengshuonan
	 * @return boolean true 已经关注 false 没有关注
	 */
	@Override
	@Transactional(readOnly = true)
	public boolean validateUserIsSub(String openId) {

		try {
			List<WechatUser> wechatUsers = this.queryCriteriaList(Restrictions.eq("wechatId", openId));

			if (wechatUsers != null && wechatUsers.size() >= 1) {
				return true;// 返回已经关注
			} else {
				return false;// 返回没有关注
			}

		} catch (Exception e) {
			log.error(" 验证该公众号是否已经关注出错 ！");
		}
		return true;// 返回已经关注
	}

	/**
	 * @Description:获取微信用户关注时的推广商id
	 * @param wechatId
	 *            微信openid
	 * @author fengshuonan
	 * @return String 推广商id
	 */
	@Override
	@Transactional(readOnly = true)
	public String getPromotionIdByWechatId(String wechatId) {

		Criterion criterion = Restrictions.eq("wechatId", wechatId);

		try {
			WechatUser wechatUser = this.queryCriteriaUnResult(criterion);

			if (wechatUser != null) {
				String promotionId = wechatUser.getPromotionId();
				if (ToolUtil.isNotBlank(promotionId)) {
					return promotionId;
				}
			}
		} catch (Exception e) {
			log.error("获取推广商id出现错误！WechatUserDaoImpl：getPromotionIdByWechatId（）");
		}

		return null;
	}

}
